<?php

namespace app\admin\model\rexam;

use think\Model;


class Question extends Model
{

    

    

    // 表名
    protected $name = 'rexam_question';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'typedata_text',
        'judgedata_text'
    ];
    

    
    public function getTypedataList()
    {
        return ['4' => __('Typedata 4')];
    }

    public function getJudgedataList()
    {
        return ['0' => __('Judgedata 0'), '1' => __('Judgedata 1')];
    }


    public function getTypedataTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['typedata']) ? $data['typedata'] : '');
        $list = $this->getTypedataList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getJudgedataTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['judgedata']) ? $data['judgedata'] : '');
        $list = $this->getJudgedataList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function subject()
    {
        return $this->belongsTo('app\admin\model\rexam\Subject', 'rexam_subject_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function load($id, $sh){
        $one = $this->get(['id'=>$id]);
        $options_json = json_decode($one['options'], true);
        if($sh && $options_json){
            shuffle($options_json);
        }
        $one['options_json']=$options_json;
        return $one;
    }

    public function check($id, $ans){
        $one = $this->get(['id'=>$id]);
        $one['options_json'] = json_decode($one['options'], true);
        $ans_json = explode(',', $ans);
        switch($one['typedata']){
            case 1://单选
                foreach ( $one['options_json'] as $vo){
                    if(!empty($vo['answer'])){
                        if($vo['key']==$ans){
                            return 1;
                        }
                    }
                }
                return 0;
                break;
            case 2://多选
                foreach ( $one['options_json'] as $vo){
                    if(empty($vo['answer'])){
                        if(in_array($vo['key'],$ans_json)){
                            return 0;
                        }
                    }else{
                        if(!in_array($vo['key'],$ans_json)){
                            return 0;
                        }
                    }
                }
                return 1;
                break;
            case 3://判断
                if($ans==$one['judgedata']){
                    return 1;
                }else{
                    return 0;
                }
                break;
        }
    }
}
